package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

func Func(w http.ResponseWriter,r *http.Request){
	http.Hijacker()
	m,err:=HttpRequest2Map(r)
	if err!=nil{
		w.Write([]byte("ok"))
		fmt.Println(err)
		return
	}
	fmt.Println(m)
	ret,_:=json.Marshal(m)
	fmt.Printf("%s",m)
	fmt.Printf("%s\n",ret)
	w.Header().Set("Content-Type","application/json")
	//io.Copy(w,strings.NewReader(string(ret)))
	// 输出json case 1：w.Write
	// case 2:io.Copy
	w.Write(ret)
}

func FuncIoCopy(w http.ResponseWriter,r *http.Request){
	m,err:=HttpRequest2Map(r)
	if err!=nil{
		w.Write([]byte("ok"))
		fmt.Println(err)
		return
	}
	fmt.Println(m)
	ret,_:=json.Marshal(m)
	fmt.Printf("%s",m)
	fmt.Printf("%s\n",ret)
	w.Header().Set("Content-Type","application/json")
	io.Copy(w,strings.NewReader(string(ret)))
}

func HttpRequest2Map(r *http.Request) (map[string]interface{}, error) {
	if r.Method == "GET" {
		return httpForm2Map(r)

	} else if r.Method == "POST" {
		return httpBody2Map(r)

	}

	return nil, errors.New("unSupport http method")
}

func httpBody2Map(r *http.Request) (map[string]interface{}, error) {
	m := make(map[string]interface{})
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(data, &m)
	if err != nil {
		return nil, err
	}
	return m, nil
}

func httpForm2Map(r *http.Request) (data map[string]interface{}, err error) {
	data = make(map[string]interface{})
	err = r.ParseForm()
	if err != nil {
		return
	}

	if len(r.Form) == 0 {
		return nil, errors.New("输入参数为空")
	}
	for i, v := range r.Form {
		if len(v) == 0 || len(v) > 1 {
			return nil, errors.New("表单输入不合法")
		}
		data[i] = v[0]
	}
	return
}
func main(){
	http.HandleFunc("/recv",Func)   // w.Write方式
	http.HandleFunc("/recv2",FuncIoCopy)  //ioCopy方式
	err:=http.ListenAndServe(":8080",nil)
	if err!=nil{
		panic(err)
	}
}
